// Copyright Druid Mechanics


#include "AI/BTService_FindNearestPlayer.h"
#include "AIController.h"
#include "BehaviorTree/BTFunctionLibrary.h"
#include "Kismet/GameplayStatics.h"

void UBTService_FindNearestPlayer::TickNode(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds)
{
	Super::TickNode(OwnerComp, NodeMemory, DeltaSeconds);
	APawn* OwningPawn = AIOwner->GetPawn();
	const FName TargetTag = OwningPawn->ActorHasTag(FName("Player")) ? FName("Enemy") : FName("Player");
	TArray<AActor*> ActorsWithTag;
	/**
	 * GetAllActorsWithTag: 寻找在世界中有特定标签的Actor。
	 * 这是一个耗时操作，不要再每一帧都使用它。
	 */
	UGameplayStatics::GetAllActorsWithTag(OwningPawn, TargetTag, ActorsWithTag);
	/**
	 * TNumericLimits: 数值限制模板。
	 */
	float ClosetDistannce = TNumericLimits<float>::Max();
	AActor* ClosetActor = nullptr;
	for(AActor* Actor : ActorsWithTag)
	{
		if(IsValid(OwningPawn)  && IsValid(Actor))
		{
			/**
			 * GetDistanceTo: 返回从此Actor到OtherActor的距离。
			 */
			const float Distance = OwningPawn->GetDistanceTo(Actor);
			if(Distance < ClosetDistannce)
			{
				ClosetDistannce = Distance;
				ClosetActor = Actor;
			}
		}
	}
	UBTFunctionLibrary::SetBlackboardValueAsObject(this, TargetToFollowSelector, ClosetActor);
	UBTFunctionLibrary::SetBlackboardValueAsFloat(this, DistanceToTargetSelector, ClosetDistannce);
}
